package com.chb.system.service.impl;

import com.chb.system.mapper.RoleMenuMapper;
import com.chb.system.service.RoleMenuService;
import com.chb.system.service.UserService;
import com.hos.entity.sys.RoleMenu;
import com.hos.entity.sys.User;
import com.hos.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ：张家琪
 * @date ：Created in 2023/12/21 15:56
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class RoleMenuServiceImpl implements RoleMenuService {
    @Autowired
    private RoleMenuMapper roleMenuMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserService userService;


    /**
     * 保存角色菜单权限信息
     * 分配权限
     *
     * @param roleId  角色ID
     * @param meunIds 菜单ID
     * @return
     */
    @Override
    public Integer saveRoleMenu(Long roleId, List<Long> meunIds) {
        int i = roleMenuMapper.deleteById(roleId);
        for (Long meunId : meunIds) {
            RoleMenu roleMenu = new RoleMenu(roleId, meunId);
            this.roleMenuMapper.insert(roleMenu);
        }
        redisTemplate.delete("menu:leftMenu:" + getUserByToken().getPhone());
        return i;
    }

    private User getUserByToken() {
        String token = WebUtil.getToken();
        String phone = redisTemplate.opsForValue().get("user:" + token);
        return userService.findUserByPhone(phone);
    }
}